package com.example.demo.controller;

import com.example.demo.entity.Message;
import com.example.demo.entity.User;
import com.example.demo.service.MessageService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;

    // 发送消息
    @PostMapping("/send")
    public Map<String, Object> sendMessage(
            @RequestParam Long postId, // 帖子 ID
            @RequestParam String actionType, // 操作类型：like（点赞）、comment（评论）、follow（关注）
            HttpServletRequest request) {

        // 获取当前用户
        User currentUser = userService.getCurrentUser(request);
        if (currentUser == null) {
            return Map.of("code", 401, "message", "用户未登录");
        }

        // 获取帖子作者
        User postAuthor = userService.getPostAuthor(postId);
        if (postAuthor == null) {
            return Map.of("code", 404, "message", "帖子作者不存在");
        }

        // 生成消息内容
        String content = generateMessageContent(currentUser, actionType);

        // 创建消息对象
        Message message = new Message();
        message.setSenderId(currentUser.getId());
        message.setReceiverId(postAuthor.getId());
        message.setContent(content);
        message.setIsRead(false);
        message.setCreatedAt(LocalDateTime.now());

        // 保存消息到数据库
        messageService.saveMessage(message);

        return Map.of("code", 200, "message", "消息发送成功");
    }

    // 获取消息列表
    @GetMapping("/list")
    public Map<String, Object> getMessageList(HttpServletRequest request) {
        // 获取当前用户
        User currentUser = userService.getCurrentUser(request);
        if (currentUser == null) {
            return Map.of("code", 401, "message", "用户未登录");
        }

        // 获取当前用户的消息列表
        List<Message> messages = messageService.getMessageList(currentUser.getId());

        // 返回消息列表
        return Map.of("code", 200, "message", "success", "data", messages);
    }

    private String generateMessageContent(User currentUser, String actionType) {
        switch (actionType) {
            case "like":
                return "用户 " + currentUser.getUsername() + " 点赞了你的帖子";
            case "comment":
                return "用户 " + currentUser.getUsername() + " 评论了你的帖子";
            case "follow":
                return "用户 " + currentUser.getUsername() + " 关注了你";
            default:
                return "用户 " + currentUser.getUsername() + " 对你的帖子执行了操作";
        }
    }
}
